
layui.define(['jquery','form'], function (exports) {
	"use strict";
	var $ = layui.jquery,form=layui.form,object = {
		c: {data:[]}, // 配置项
		f: function (c) { // 数据初始化
			var s=new Date().getTime(),t = this;
			t.c.id = c.id?c.id:'simple_table_TP_ProductBqSp';
			t.c.tableId = c.tableelem?c.tableelem:'table-'+s;
			t.c.data = c.data; // 数据

			//将表单数据带入js
			t.c.formObj = c.formObj;
			/**自定义的字段，是否流转中**/
			t.c.onProcess = c.onProcess;

			//复选框选中，存放行号
			t.c.checkedIndex = [];
		},
        load:function () { // 加载控件
        	var h = ``
				+ `<div class="layui-form layui-form-item" lay-filter="` + this.id + `" style="background-color: #ffffff;padding-top: 10px;padding-bottom: 10px;">`
    				+ `<label style="font-weight: 700;font-size: 18px; padding: 15px;">子件列表</label>`
        		+ `</div>`
			if(this.c.onProcess == 0) {
				h += `<div class="layui-table-tool" style="padding-top: 0; min-height: 0; background-color: #ffffff;width: auto;">`
					+ `<div class="layui-table-tool-temp">`
					+ `<div class="layui-btn-container">`
					+ `<a class="layui-btn layui-btn-normal layui-btn-sm " lay-event="event-to-select"><i class="iconfont icon-add-btn"></i>新增</a>`
					+ `<a class="layui-btn layui-btn-danger layui-btn-sm " lay-event="event-to-del" ><i class="layui-icon layui-icon-delete">删除</a>`
					+ `</div>`
					+ `</div>`
					+ `</div>`
			}
            	h+= `<div class="layui-form layui-form-item" pane>`
            		+ `<div id="`+this.c.tableId+`">`
            			+ this.loadTable()
            		+ `</div>`
        		+ `</div>`
    		+ `</div>`;
            $('#'+this.c.id).html(h);
            this.listenBtn();
			this.listenBtnByTd();
        },
        loadTable:function () { // 加载表格
            return ``
        	+ `<div class="layui-table-box">`
        		+ `<div class="layui-table-header" style="height: 300px; max-height: 300px; overflow: auto; background-color: #ffffff;">`
	            	+ `<table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="grid" lay-even="" style="margin: 0;">`
	            		+ `<thead>`
	            			+ this.loadTableOfThead()
	            		+ `</thead>`
	            		+ `<tbody>` + this.loadTableOfTbody()+`</tbody>`
	        		+ `</table>`
        		+ `</div>`
    		+ `</div>`;
        },
        loadTableOfThead:function () { // 加载表头
            var h = `<thead>`;
			h +=`<tr>`;
			h += `<th style="display: none;">id</th>`;
			if (this.c.onProcess == 0) {
				h += `<th style="width:1.9%; text-align: center; color: #000000;padding: 0 !important;">
							<input type="checkbox" id="checkAll" lay-skin="primary" lay-filter="checkAll">
						</th>`;
			}
			h += `<th style="width:5%; text-align: center; color: #000000;">母件编码</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">子件编码</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">子件名称</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">子件数量</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">子件单价</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">采购链接</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">铺货标识</th>`;
			h += `<th style="width:5%; text-align: center; color: #000000;">子件备注</th>`;
            h += `</tr>`;
            h + `</thead>`;
			return h;
        },
		loadTableOfTbody:function () { // 加载表tbody
			var t = this;
			var h = `<tbody id="tbody">`;
			for(var i=0;i<t.c.data.length;i++){
				h += `<tr id="table_th_`+i+`">`;
				h += t.loadTableTdOfTbody(t.c.data[i],i);
				h+= `</tr>`;
			}
			h += `</tbody>`;
			return h;
		},
		loadTableTdOfTbody: function (data,i) { // 加载表tbody
			var h =`<td style="display: none;">` + data.id + `</td>`;
			if (this.c.onProcess == 0) {
				h += `<td style="text-align:center;padding:0;">
					<input type="checkbox" class="chBox"  lay-skin="primary" data-index="` + i + `"  lay-filter="checkBoxOne">
					</td>`;
			}
			h += `<td style="text-align:center; padding: 0;">` + data.pcode + `</td>`;
			h += `<td style="text-align:center; padding: 0;">` + data.code + `</td>`;
			h += `<td style="text-align:center;padding:0;"><input type="text" maxlength="400"  class="text_align_center layui-input"  lay-filter="_input"  data-type="name" value="` + (data.name!=undefined?data.name:'') + `" data-index="` + i + `"></td>`;
			h += `<td style="text-align:center;padding:0;"><input type="number" maxlength="15"  min="0.01" class="text_align_center layui-input"  lay-filter="_input"  data-type="num" value="` + (data.num!=undefined?data.num:'') + `" data-index="` + i + `"></td>`;
			h += `<td style="text-align:center;padding:0;"><input type="number" maxlength="15"  min="0.01" class="text_align_center layui-input"  lay-filter="_input"  data-type="bprice" value="` + (data.bprice!=undefined?data.bprice:'') + `" data-index="` + i + `"></td>`;
			h += `<td style="text-align:center;padding:0;"><input type="text" maxlength="500"  class="text_align_center layui-input"  lay-filter="_input"  data-type="linkIn" value="` + (data.linkIn!=undefined?data.linkIn:'') + `" data-index="` + i + `"></td>`;
			h += `<td style="text-align:center;padding:0;"><input type="number" maxlength="15"  min="0" class="text_align_center layui-input"  lay-filter="_input"  data-type="linkInMark" value="` + (data.linkInMark!=undefined?data.linkInMark:'') + `" data-index="` + i + `"></td>`;
			h += `<td style="text-align:center;padding:0;"><input type="text" maxlength="200"  class="text_align_center layui-input"  lay-filter="_input"  data-type="remark" value="` + (data.remark!=undefined?data.remark:'') + `" data-index="` + i + `"></td>`;
			return h;
        },
        listenBtn:function () { // 添加监听
            var t = this;

            // 监听“新增”按钮
            $('a[lay-event="event-to-select"]').on('click',function (e) {
				var rowCurrent = {};
				rowCurrent.id = null;
				rowCurrent.pcode = t.c.formObj.getValueByName('code');
				rowCurrent.code = '保存后自动生成';
				rowCurrent.name = '';
				rowCurrent.num = 1;
				rowCurrent.bprice = 1;
				rowCurrent.linkIn = "";
				rowCurrent.linkInMark = "";
				rowCurrent.remark = "";
				t.addRow(rowCurrent);
            });

			//全选
			layui.form.on('checkbox(checkAll)', function(data){
				var elem = data.elem;
				$(".chBox").prop("checked", elem.checked);
				var checkedIndex = [];
				$(".chBox").each(function(k, v){
					if ($(v).is(':checked')) {
						checkedIndex.push($(v).attr('data-index'));
					}
				});
				t.c.checkedIndex = checkedIndex;
				layui.form.render();
			});
			// 列表里的小选择框点击
			layui.form.on('checkbox(checkBoxOne)', function(data){
				var elem = data.elem;
				if ($(".chBox").not('input:checked').length) {
					$('#checkAll').prop("checked", false);
				} else {
					$('#checkAll').prop("checked", true);
				}
				var checkedIndex = [];
				$(".chBox").each(function(k, v){
					if ($(v).is(':checked')) {
						checkedIndex.push($(v).attr('data-index'));
					}
				});
				t.c.checkedIndex = checkedIndex;
				layui.form.render();
			});

			// 监听“删除”按钮
			$('a[lay-event="event-to-del"]').on('click',function (e) {
				var checkedIndexList = t.c.checkedIndex;
				if (checkedIndexList.length ==0 || checkedIndexList==null){
					return layer.msg("请至少选择一条要删除的数据!");
				}
				if (checkedIndexList.length >= t.c.data.length){
					return layer.msg("删除失败,子件列表至少需要一条!");
				}

				var oldData = [];
				for (var i = 0; i < t.c.data.length; i++) {
					var isOld = false;
					for (var j = 0; j < checkedIndexList.length; j++) {
						if(i == checkedIndexList[j] && t.c.data[i].id!=null){
							isOld = true;
						}
					}
					if(isOld){
						oldData.push(t.c.data[i].id);
					}
				}
				if(oldData.length>0){
					t.delYes(oldData,checkedIndexList);
				}else{
					var newData = [];
					for (var i = 0; i < t.c.data.length; i++) {
						var isDel = false;
						for (var j = 0; j < checkedIndexList.length; j++) {
							if(i == checkedIndexList[j]){
								isDel = true;
							}
						}
						if(!isDel){
							newData.push(t.c.data[i]);
						}
					}
					t.c.data = newData;
					$('#' + t.c.id).empty();
					return t.reload(t.c);
				}

			});
        },

		listenBtnByTd:function () { // 添加监听
			var t = this;
			var domTable = $('#' + t.c.tableId);
			//监听表格中的input框的值修改
			domTable.find('input[lay-filter="_input"]').off('blur');
			domTable.find('input[lay-filter="_input"]').on('blur',function (e) {
				var indexOfRow = $(this).attr('data-index');
				var dataType = $(this).attr('data-type');
				var priceIn = 0;
				for (var i = 0; i < t.c.data.length; i++) {
					if(i ==  Number(indexOfRow)){
						if (dataType == 'num'){
							t.c.data[i].num = t.toFixed(e.delegateTarget.value,2)
						} else if (dataType == 'bprice'){
							t.c.data[i].bprice = t.toFixed(e.delegateTarget.value,2)
						}else if (dataType == 'linkIn'){
							t.c.data[i].linkIn = e.delegateTarget.value
						}else if (dataType == 'linkInMark'){
							t.c.data[i].linkInMark = t.toFixed(e.delegateTarget.value,0)
						}else if (dataType == 'remark'){
							t.c.data[i].remark = e.delegateTarget.value
						} else if (dataType == 'name'){
							t.c.data[i].name = e.delegateTarget.value
						}
					}
					priceIn = priceIn + (Number(t.c.data[i].num) * Number(t.c.data[i].bprice))
				}
				t.c.formObj.setValueByName("priceIn",t.toFixed(priceIn,2));

				// $('#' + t.c.id).empty();
				// return t.reload(t.c);
				var h = t.loadTableTdOfTbody(t.c.data[Number(indexOfRow)],Number(indexOfRow));
				$('#table_th_' + indexOfRow).html(h);
				t.listenBtnByTd();
			});


			// 表单控件重新加载
			form.render();
		},

		//删除弹框
		toDel:function(spId,indexOfRow) {
			var t = this;
			var c = this.c;
			var loadIndex = layer.confirm('确定要删除该子件信息?', {icon: 3}, function () {
				//点击确定的回调
				layer.close(loadIndex);
				if (t.c.data.length == 1){
					return layer.msg("删除失败,子件列表至少需要一条!");
				}
				if (spId == null){
					var newData = [];
					for (var i = 0; i < t.c.data.length; i++) {
						if(i != indexOfRow){
							newData.push(c.data[i]);
						}
					}
					c.data = newData;
					$('#' + c.id).empty();
					return t.reload(c);
				} else {
					t.delYes(spId);
				}

			}, function () {});//点击取消的回调
		},
		//确定删除
		delYes:function(spId,checkedIndexList){
			var t = this;
			var c = this.c;
			var loadIndex = layer.load(2);
			$.ajax({
				url: '/api/inter/tpProductBqSp/del',
				data: "list="+spId+"&code="+t.c.formObj.getValueByName('code'),
				type: 'POST',
				async: true,
				success: function (result) {
					if(result.code==0){
						layer.close(loadIndex);
						layer.msg("操作成功", {icon: 1});
						//表格重载
						var newData = [];
						for (var i = 0; i < c.data.length; i++) {
							var isDel = false;
							for (var j = 0; j < checkedIndexList.length; j++) {
								if(i==checkedIndexList[j]){
									isDel = true;
								}
							}
							if(!isDel){
								newData.push(c.data[i]);
							}
						}
						c.data = newData;
						$('#' + c.id).empty();
						return t.reload(c);

					}else {//失败
						layer.close(loadIndex);
						layer.msg(result.msg, {icon: 2});
					}
				},
				error: function () {
					layer.close(loadIndex);
					layer.msg("删除失败，请稍后再试！", {icon: 2});
				}
			});
		},

        removeRow:function(index) { // 重新加载表格
        	var t = this;
        	t.c.data.splice(index, 1);
			return t.reload(t.c);
        },
        reloadTable:function () { // 重新加载表格
            $('#'+this.c.tableId).html(this.loadTable());
            this.listenBtn();
        },
        getData:function () {
            return this.c.data;
        },
        init:function (c) {this.f(c);this.load();return object;},
        reload:function (c) {c.data = this.c.data;$('#' + this.c.id).empty();return this.init(c);},
        addRow:function (row) {
			var c = this.c;
			var t = this;
			c.data.push(row);
			var h =  `<tr id="table_th_`+(c.data.length-1)+`">`;
			h += t.loadTableTdOfTbody(row,c.data.length-1);
			h+= `</tr>`;
			$('#tbody').append(h);
			t.listenBtnByTd();
        },
        addRows:function (rows) {
        	var c = this.c;
        	for (var i = 0; i < rows.length; i++) {
	        	c.data.push(rows[i]);
			}
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        editRow:function (index, row) {
        	var c = this.c;
			c.data[index] = row;
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        editRowOfAttr:function (index, row) {
        	var c = this.c;
        	for(var key in row){
        		c.data[index][key] = row[key]
        	}
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        reloadRows:function (rows) {
        	var c = this.c;
        	c.data = rows;
        	return this.reload(c);
        },
		//重写toFixed方法
		toFixed:function(number, precision) {
			if (Number.isInteger(Number(number))) {
				return number;
			}
			number = Math.round(+number + 'e' + precision) / Math.pow(10, precision) + '';
			let s = number.split('.');
			if ((s[1] || '').length < precision) {
				s[1] = s[1] || '';
				s[1] += new Array(precision - s[1].length).fill('0').join('');
			}
			return s.join('.');
		}
	};
	exports('simple_table_TP_ProductBqSp', object);
});